
#include "LogUtil.h"

#include <sys/time.h>
#include <time.h>

#include <cstdlib>
#include <iomanip>
#include <fstream>

using namespace std;

__BEGIN_NAMESPACE_DECL_

// Static members
LogLevel LogUtil::level_ = LOGUTIL_LEVEL;
LogLevel LogUtil::Level() { return LogUtil::level_; }

//static fstream fb("log.txt", iostream::out);

void LogUtil::SetLevel (LogLevel level) { level_ = level; }

// Constructor
LogUtil::LogUtil()
    : exitFlag(false)
{
}

// Destructor
LogUtil::~LogUtil()
{
    LOGUTIL_STREAM << os_.str() << endl;
    if (exitFlag)
        exit(EXIT_FAILURE);
    //fb << os_.str() << endl;
}

// static Get
std::ostringstream& LogUtil::Get (LogLevel level)
{
    const char *levelStr;
    char timeStr[100];
    time_t t;
    struct tm *tmp;
    struct timeval tv;

    t = time(NULL);
    tmp = localtime(&t);
    gettimeofday (&tv, NULL);
    strftime (timeStr, 100, "%d-%b-%Y %H:%M:%S", tmp);

    os_ << "[" << timeStr << "." << setw(3) << setfill ('0') << (tv.tv_usec/1000) << "] ";

    switch (level) 
    {
        case LEVEL_DEBUG: levelStr = "DEBUG"; break;
        case LEVEL_INFO:  levelStr = "INFO";  break;
        case LEVEL_WARN:  levelStr = "WARN";  break;
        case LEVEL_ERROR: levelStr = "ERROR"; break;
        case LEVEL_FATAL: levelStr = "FATAL"; break;
    }

    os_ << left << setw(5) << setfill(' ') << levelStr << " ";

    if (level == LEVEL_FATAL)
        exitFlag = true;

    return os_;
}

__END_NAMESPACE_DECL_


